<template>
  <div class="wrap">

    <div class="header">
      <div class="left">
        <el-select
          v-model="queryParams.accountType"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
        >
          <el-option :label="$t('common.allStores')" value=""></el-option>
          <el-option :label="$t('common.Single store')" :value="1"></el-option>
          <el-option :label="$t('common.Multiple Stores')" :value="2"></el-option>
        </el-select>

        <el-select
          v-model="queryParams.platformType"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
          v-if="$store.getters.platformNum > 1"
        >
          <el-option :label="$t('shipment.allPlatforms')" value=""></el-option>
          <el-option
            v-for="item in platformTypeList"
            :key="item.value"
            :label="item.name"
            :value="item.value"></el-option>
        </el-select>

        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
          v-if="false"
        >
          <el-option :label="$t('picking.All states')" value=""></el-option>
          <el-option :label="$t('user.In cooperation')" :value="1"></el-option>
          <el-option :label="$t('user.Stop cooperation')" :value="2"></el-option>
        </el-select>


      </div>
      <div class="right">

        <div style="display: inline-block;width: 360px">
          <el-input
            size="small"
            style="width: 200px; margin-right: 10px; margin-bottom: 10px"
            v-model="queryParams.keyword"
            :placeholder="$t('common.Search for store or username')"
            @keyup.enter.native="changeOption(true)"
            clearable @clear="changeOption(false, 'clear')"
          ></el-input>
          <el-button size="small" type="primary" @click="changeOption(true)">{{ $t('common.search') }}</el-button>
          <el-button @click="showUserDialog" class="mgl20" type="warning">{{ $t('user.create an account') }}</el-button>
        </div>

      </div>

    </div>
    <div class="content">
      <el-table
        v-loading="loading"
        :data="data"
        border
        @sort-change="handleSortChange"
        v-tableHeight="{bottomOffset: 80}"
        height="100px"
        ref="tableData"
      >
        <el-table-column
          prop="account"
          :label="$t('table.user name')"
          align="center"
          min-width="120"
          fixed
        >
          <template slot-scope="{row}">
            <diy-link @click="jumpInfo(row)">{{row.account}}</diy-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="accountTypeArr"
          :label="$t('table.platform')"
          min-width="150"
          align="center"
          v-if="$store.getters.platformNum > 1"
        >
          <template slot-scope="{row}">
            <template v-if="row.accountTypeArr.length === 0">
              -
            </template>
            <template v-else-if="row.accountTypeArr.length === 1">
              {{row.accountTypeArr[0]}}
            </template>
            <template v-else>
              <el-tooltip class="item" effect="dark" placement="top-end">
                <div slot="content">
                  <div
                    v-for="item in row.accountTypeArr"
                    :key="item"
                  >
                    {{item}}
                  </div>
                </div>
                <div>{{ row.accountTypeArr.length }}</div>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="accountList"
          :label="$t('order.Shop Name')"
          align="center"
          min-width="100"
        >
          <template slot-scope="{row}">
            <template v-if="row.accountList.length === 0">
              {{ $t('user.Not authorized yet') }}
            </template>
            <template v-else-if="row.accountList.length === 1">
              {{ row.accountList[0].nickname }}
            </template>
            <template v-else>
              <el-tooltip class="item" effect="dark" placement="top-end">
                <div slot="content">
                  <div
                    v-for="accountItem in row.accountList"
                    :key="accountItem.accountId"
                  >
                    {{accountItem.accountType}}，{{accountItem.nickname}}
                  </div>
                </div>
                <div>{{ row.accountList.length }}</div>

              </el-tooltip>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNum"
          :label="$t('table.Total order quantity')"
          align="center"
          min-width="100"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="stickerNum"
          :label="$t('table.Number of processed stickers')"
          align="center"
          min-width="150"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="finishStickerNum"
          :label="$t('table.Completed OEM order quantity')"
          align="center"
          min-width="150"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="stockNum"
          :label="$t('table.Total inventory')"
          align="center"
          min-width="100"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="totalStickerFee"
          :label="$t('table.Total revenue from stickers')"
          align="center"
          min-width="150"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="sumGoodsMiddleIncome"
          :label="$t('table.大货中转总收入（元）')"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="sumShipmentTallying"
          :label="$t('table.理货总收入（元）')"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="sumStorageFee"
          :label="$t('table.Warehousing fee income')"
          align="center"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="totalFee"
          :label="$t('table.Total income')"
          align="center"
          min-width="150"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="admins"
          :label="$t('table.Operational')"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            {{getAdminAccount(row.admins)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="$t('table.createTime3')"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="status"
          :label="$t('table.status')"
          align="center"
          min-width="100"
        >
          <template slot-scope="{row}">
            {{row.status === 1 ? $t('user.In cooperation') : $t('user.Stop cooperation')}}
          </template>
        </el-table-column>

      </el-table>
      <div class="page-wrap">
        <el-pagination
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-size="queryParams.pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>


    </div>

    <el-dialog
      :title="$t('user.create an account')"
      :visible.sync="userDialog"
      width="700px"
    >
      <el-form
        ref="userForm"
        :model="dialogForm" label-width="130px"
        :rules="rules"
      >
        <el-form-item :label="$t('table.user name')" prop="account">
          <el-input v-model.trim="dialogForm.account"></el-input>
        </el-form-item>
        <el-form-item :label="$t('login.password')" prop="password">
          <el-input v-model.trim="dialogForm.password">
            <template slot="append">
              <el-button @click="createPassword">{{ $t('user.random') }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('user.email')" prop="email">
          <el-input v-model="dialogForm.email"></el-input>
          <div class="form-tips font-grey">
            {{ $t('user.createAccountText1') }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('一件代发权限')" prop="oneShippingAdminId">
          <el-select v-model="dialogForm.oneShippingAdminId" placeholder="点击选择运营账户">
            <el-option
              v-for="item in oneShippingAdminList"
              :key="item.adminId"
              :label="item.account"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('中转送仓权限')" prop="middleTransferAdminId">
          <el-select v-model="dialogForm.middleTransferAdminId" placeholder="点击选择运营账户">
            <el-option
              v-for="item in middleTransferAdminList"
              :key="item.adminId"
              :label="item.account"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库分拣权限" prop="inboundSortingAdminId">
          <el-select v-model="dialogForm.inboundSortingAdminId" placeholder="点击选择运营账户">
            <el-option
              v-for="item in inboundSortingAdminList"
              :key="item.adminId"
              :label="item.account"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="userDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button @click="createUser" :loading="userLoading" type="primary">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {generateRandomString, getFalabellaName, getMercadoName, isEmail} from "@/utils";
import request from "@/utils/request";
import {createUser, getUserList} from "@/api/user";
import {getAllAdmin} from "@/api/admin";
import {ROLE_INBOUND_SORTING, ROLE_MIDDLE_TRANSFER, ROLE_ONE_SHIPPING, ROLE_OPERATE} from "@/utils/admin";

export default {
  name: "userList",
  computed: {
    oneShippingAdminList(){
      return this.adminList.filter(item=>{
        return item.roles.indexOf(ROLE_ONE_SHIPPING) !== -1
      })
    },
    middleTransferAdminList(){
      return this.adminList.filter(item=>{
        return item.roles.indexOf(ROLE_MIDDLE_TRANSFER) !== -1
      })
    },
    inboundSortingAdminList(){
      return this.adminList.filter(item=>{
        return item.roles.indexOf(ROLE_INBOUND_SORTING) !== -1
      })
    }
  },
  data(){

    const checkEmail = (rule,value,callback) => {
      request({
        url: '/user/checkEmail',
        method: 'get',
        params: this.dialogForm,
        handleError: true,
      }).then(res=>{
        if(res.error !== 0){
          callback(new Error(res.message));
        }else{
          callback();
        }
      })
    }

    const checkAccount = (rule, value, callback) => {
      request({
        url: '/user/checkAccount',
        method: 'get',
        params: this.dialogForm,
        handleError: true,
      }).then(res=>{
        if(res.error !== 0){
          callback(new Error(res.message));
        }else{
          callback();
        }
      })
    }

    return {
      queryParams:{
        page: 1,
        pageSize: 20,
        accountType : '',
        status : '',
        adminId : '',
        tabType: '',
        platformType: '',
      },
      data: [],
      loading: false,
      userLoading: false,
      total: 0,
      platformTypeList: [],
      userDialog: false,
      is_search: false,
      sortOrders: ['descending', 'ascending', null],
      dialogForm: {
        account: '',
        password: '',
        email: '',
        oneShippingAdminId: '',
        middleTransferAdminId: '',
        inboundSortingAdminId: '',
      },
      adminList: [],
      rules: {
        account: [
          { required: true, message: this.$t('common.pleaseFillIn'), trigger: 'blur'},
          { message: this.$t('user.userValid1'), trigger: 'blur',min: 3},
          { message: this.$t('user.userValid2'), trigger: 'blur',max: 20},
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/ , message: this.$t('user.userValid3'),trigger: 'blur' },
          { validator:checkAccount, trigger: 'blur' },
        ],
        password: [
          {required: true, message: this.$t('user.userValid4'), trigger: 'blur', min:6 },
          {required: true, message: this.$t('user.userValid4'), trigger: 'change', min:6 },
          {message: this.$t('user.userValid5'), trigger: 'blur', max: 30 },
        ],
        email: [
          // { required: true, message: this.$t('common.pleaseFillIn') ,trigger: 'blur' }, // 校验邮箱格式
          { pattern: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/, message: this.$t('user.userValid6') ,trigger: 'blur' },
          { validator:checkEmail ,trigger: 'blur' }, // 校验邮箱格式
        ],
        oneShippingAdminId: [
          { required: true, message: this.$t('common.请选择'), trigger: 'change'},
        ],
        middleTransferAdminId: [
          { required: true, message: this.$t('common.请选择'), trigger: 'change'},
        ],
        inboundSortingAdminId: [
          { required: true, message: this.$t('common.请选择'), trigger: 'change'},
        ],
      },
    }
    // /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
  },
  created() {
    if(this.$route.name === 'invalidUserList'){
      this.queryParams.tabType = 'invalid'
    }else if(this.$route.name === 'normalUserList'){
      this.queryParams.tabType = 'normal'
    }
    this.getData();
    this.getAdminList();
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableData'].doLayout();
    })
  },
  methods: {
    getFalabellaName,
    getMercadoName,
    getData(){
      this.loading = true
      getUserList(this.queryParams)
        .then(res=>{
          this.loading = false
          this.data = res.data
          this.total = res.info.total
          this.platformTypeList = res.info.platformTypeList
        })
    },
    getAdminList(){
      getAllAdmin()
        .then(res=>{
          this.adminList = res.data
        })
    },
    // 生成随机密码
    createPassword(){
      this.dialogForm.password = generateRandomString()
    },
    // 创建用户
    createUser(){
      this.$refs.userForm.validate(valid => {
        if(valid){
          this.userLoading = true
          createUser(this.dialogForm)
            .then(res=>{
              this.userLoading = false
              if(res.error === 0){
                this.$successMessage(res.message);
                this.userDialog = false; // 关闭弹窗
                this.resetForm();
                this.getData(); // 重新请求数据
              }else{
                this.$errorMessage(res.message);
              }
            })
        }
      })

    },
    // 重置表单
    resetForm(){
      this.dialogForm.password = '';
      this.dialogForm.account = '';
      this.dialogForm.email = '';
    },
    changeOption(is_search = false, type = ''){
      if (is_search == true) {
        //判断是否使用过搜索按钮
        this.is_search = true
      }
      if (type == 'clear') {
        if (this.is_search == false) {
          return
        } else {
          this.is_search = false
        }
      }

      this.queryParams.page = 1;
      this.getData()
    },
    //排序
    handleSortChange(column){
      this.queryParams.orderBy = ''
      this.queryParams.orderField = ''
      if(column.order){
        this.queryParams.orderBy = column.order
        this.queryParams.orderField = column.prop
      }
      this.queryParams.page = 1;
      this.getData()
    },
    jumpInfo(row){
      this.$router.push({
        name: 'userInfo',
        query: {
          id: row.id
        }
      })
    },

    getAdminAccount(admins){
      const name = [];
      admins.forEach(item=>{
        name.push(item.account)
      })
      return name.join('、')
    },
    showUserDialog(){
      this.$router.push({
        name: 'addUser',
        query: {

        }
      })
      // return ;
      // this.userDialog = true
      // this.dialogForm.account = '';
      // this.dialogForm.email = '';
      // this.dialogForm.password = ''
      // this.dialogForm.oneShippingAdminId = ''
      // this.dialogForm.middleTransferAdminId = ''
      // this.dialogForm.inboundSortingAdminId = ''

      // if(this.oneShippingAdminList.length === 1){
      //   this.dialogForm.oneShippingAdminId = this.oneShippingAdminList[0].adminId
      // }
      // if(this.middleTransferAdminList.length === 1){
      //   this.dialogForm.middleTransferAdminId = this.middleTransferAdminList[0].adminId
      // }
      // if(this.inboundSortingAdminList.length === 1){
      //   this.dialogForm.inboundSortingAdminId = this.inboundSortingAdminList[0].adminId
      // }
    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }

}
.header-select{
  margin-right: 20px;
}
.form-tips{
  line-height: 20px;
  font-size: 12px;
}
</style>
